package net.livingflow.web.resource;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.ws.rs.Path;

import net.livingflow.Constants;
import net.livingflow.model.Account;
import net.livingflow.model.Flow;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author xueqiang.mi
 * @since 2011-1-5
 */
@Path("/friFlows")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class FriendsFlowsResource extends BaseResource {

	private List<Account> friends;

	public Collection<Flow> getFlows() {
		Set<Flow> flows = new TreeSet<Flow>(new Comparator<Flow>() {
			@Override
			public int compare(Flow o1, Flow o2) {
				return o1.getCrtDate().compareTo(o2.getCrtDate());
			}
		});
		if (getFriends() != null) {
			for (Account acc : getFriends()) {
				List<Flow> list = flowService.getLattestByUser(acc.getName(), Constants.MIN_SIZE);
				flows.addAll(list);
			}
		}
		return flows;
	}

	public List<Account> getFriends() {
		if (friends == null) {
			queryFriends();
		}
		return friends;
	}

	private void queryFriends() {
		Account account = accountService.get(getUserName());
		if (account == null) {
			return;
		}

		Collection<String> fridNames = account.getFriends();
		List<Account> friends = new ArrayList<Account>();
		for (String fridName : fridNames) {
			Account friend = accountService.get(fridName);
			friends.add(friend);
		}
		this.friends = friends;
	}
}
